package cn.shiwei.basic.util;

import cn.shiwei.user.domain.Logininfo;
import cn.shiwei.user.mapper.LogininfoMapper;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.http.HttpServletRequest;

public class LoginContextUtil {

    public static Object getFactoryObj(String objName, HttpServletRequest request){
        WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());
        return webApplicationContext.getBean(objName);
    }

    public static Logininfo getLoininfo(HttpServletRequest request){
        String token = request.getHeader("token");
        if (!StringUtils.isEmpty(token)) {
            RedisTemplate redisTemplate = (RedisTemplate)getFactoryObj("redisTemplate", request);
            Object obj = redisTemplate.opsForValue().get(token);
            if (obj != null){
                return (Logininfo)obj;
            }
        }
        return null;
    }
    public static Logininfo getLoininfo(){
        HttpServletRequest request =
                ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
        return (Logininfo) getLoininfo(request);
    }




}
